package com.example.shardingjdbc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shardingjdbc.entity.Jy;
import com.example.shardingjdbc.service.JyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 表_20230511(Jy20230501)表控制层
 *
 * @author makejava
 * @since 2023-05-10 15:20:25
 */
@RestController
@RequestMapping("jy20230501")
@Api("ShardingJDBC分表测试")
public class JyController {
    @Resource
    JyService jyService;

    @GetMapping("/serve")
    @ApiOperation("添加")
    public void serve() {
        Jy jy = new Jy();
        jy.setAge(99);
        jy.setName("测试");
        jy.setCreateTime(new Date());
        jyService.save(jy);

    }

    @PostMapping("/batchInsert")
    @ApiOperation("批量添加十万条数据")
    public String batchInsert() {
        List<Jy> userList = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            Jy user = new Jy();
            user.setName("User" + i);
            user.setAge(i % 100);
            userList.add(user);
        }
        jyService.saveBatch(userList);
        return "success";
    }

    @PostMapping("/batchInsertUsers")
    @ApiOperation("分批次添加5000万条数据")
    public void batchInsertUsers() {
        List<Jy> userList = new ArrayList<>();
        for (int i = 0; i < 50000000; i++) {
            Jy user = new Jy();
            user.setName("user" + i);
            user.setAge(i % 50000000);
            userList.add(user);
            if (i % 1000 == 0) { // 每1000条数据插入一次
                jyService.saveBatch(userList);
                userList.clear();
            }
        }
        if (!userList.isEmpty()) { // 最后不足1000条的数据也要插入
            jyService.saveBatch(userList);
        }
    }

    /**
     * 范围查询
     */
    @GetMapping("/getUserBetweenCreateTime")
    @ApiOperation("范围查询")
    public List<Jy> getUserBetweenCreateTime() {
        Date startTime = new Date(2023 - 1900, 4, 20, 0, 0, 0); // 2023-05-20 00:00:00
        Date endTime = new Date(2023 - 1900, 4, 23, 23, 59, 59); // 2023-05-23 23:59:59
        QueryWrapper<Jy> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("create_time", startTime, endTime);
        return jyService.list(queryWrapper);
    }

}